
package com.joysuch.wwyt.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;

import info.monitorenter.cpdetector.io.ASCIIDetector;
import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;
import info.monitorenter.cpdetector.io.ParsingDetector;
import info.monitorenter.cpdetector.io.UnicodeDetector;

import javax.servlet.http.HttpServletRequest;

import static java.awt.SystemColor.info;

public class FileUtil {

    public static String getFileEncoding(File file, String defaultCharset) {
        String encoding = getFileEncoding(file);
        return encoding == null ? defaultCharset : encoding;
    }

    public static String getFileEncoding(File file) {
        String charsetName = null;
        try {
            CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
            detector.add(new ParsingDetector(false));
            detector.add(JChardetFacade.getInstance());
            detector.add(ASCIIDetector.getInstance());
            detector.add(UnicodeDetector.getInstance());
            java.nio.charset.Charset charset = null;
            charset = detector.detectCodepage(file.toURI().toURL());
            if (charset != null) {
                charsetName = charset.name();
            } else {
                // 选取平台默认编码
                charsetName = Charset.defaultCharset().name();// "UTF-8";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return charsetName;
    }

    public static String getFileEncoding(String filePath) {
        return getFileEncoding(new File(filePath));
    }

    public static String getEncodeFileName(HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
        String agent = request.getHeader("User-Agent");
        if (agent.contains("MSIE")) {
            // IE浏览器
            fileName = URLEncoder.encode(fileName, "utf-8");
            fileName = fileName.replace("+", " ");
        } else {
            // 其它浏览器
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
        return fileName;
    }

    public static String replaceFileNameSpecialCharacters(String fileName) {

        /*
         * 文件名中不能含有：\ / : * ? " < > | 英文的这些字符 ，这里使用"."、"'"进行替换。
         * \/:?| 用.替换
         * "<> 用'替换
         */
        fileName = fileName.replaceAll("[/\\\\:*?|]", "_");
        fileName = fileName.replaceAll("[\"<>]", "_");

        return fileName;
    }

    public static void main(String[] args) {
        // 精馏单元-1_2PCE装置.png
        System.out.println(replaceFileNameSpecialCharacters("精馏单元-1/2PCE装置"));
    }

}
